package ThreadSafeDemo;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Account {
    private String cardId;
    private double money;
    //创建一个锁对象
    private final Lock lk = new ReentrantLock();
    public Account() {
    }

    public Account(String cardId, double money) {
        this.cardId = cardId;
        this.money = money;
    }
    //小明小红进程同时过来
    public  void drawMoney(double money) {
        //判断是谁来取钱
        String name = Thread.currentThread().getName();
        try {
            lk.lock();//加锁
            //1.判断余额是否足够
            System.out.println("欢迎来到好呀好呀银行~当前账户余额"+this.money+"CNY");
            if (this.money>=money){
                System.out.println(name+"来取钱"+money+"成功");
                this.money-=money;
                System.out.println(name+"取钱后账户余额为"+this.money);
            }else {
                System.out.println(name+"来取钱，余额不足,当前账户余额为"+this.money);
            }

        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            lk.unlock();//解锁
        }
    }
    public String getCardId() {
        return cardId;
    }

    public void setCardId(String cardId) {
        this.cardId = cardId;
    }

    public double getMoney() {
        return money;
    }

    public void setMoney(double money) {
        this.money = money;
    }


}
